package com.uziot.bucket.retry.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.ResourceAccessException;

import java.time.LocalTime;

/**
 * @author shidt
 * @version V1.0
 * @className Test
 * @date 2019-04-23 12:59:00
 * @description
 */
@Slf4j
@RestController
public class RetryController {

    /**
     * Retryable的参数说明：
     * <p>
     * value：抛出指定异常才会重试
     * include：和value一样，默认为空，当exclude也为空时，默认所以异常
     * exclude：指定不处理的异常
     * maxAttempts：最大重试次数，默认3次
     * backoff：重试等待策略，默认使用@Backoff，@Backoff的value默认为1000L，
     * 我们设置为2000L；multiplier（指定延迟倍数）默认为0，表示固定暂停1秒后进行重试，
     * 如果把multiplier设置为1.5，则第一次重试为2秒，第二次为3秒，第三次为4.5秒。
     */

    @Retryable(value = ResourceAccessException.class, maxAttempts = 5,
            backoff = @Backoff(delay = 1000L, multiplier = 2))
    @GetMapping(value = "apply")
    public String reply() {
        log.info("请求数据...");
        return exceptionTest();
    }

    @Recover
    public String recover(ResourceAccessException e) throws Exception {
        e.printStackTrace();
        log.error("减库存失败！！！" + LocalTime.now());
        throw new Exception(e.getCause() + e.getMessage());
    }


    public String exceptionTest() {
        throw new ResourceAccessException("I/O error on POST request for \"www.uziot.com\": Connection timed out: connect; nested exception is java.net.ConnectException: Connection timed out: connect");
    }

}
